﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.wdx;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.OperationaldecisionsCommand;
using MedicalPCTerminal.Read.API.Dtos;
using SqlSugar;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.OperationaldecisionsHandler
{
    /// <summary>
    /// 决策层级
    /// </summary>
    public class ManagementOverviewHandler : IRequestHandler<ManagementOverviewCommand, ApiPaging<ManagementOverviewDto>>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        private readonly IMapper mapper;
        private readonly SqlSugarContext sugar;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="sugar"></param>
        public ManagementOverviewHandler(IMapper mapper, SqlSugarContext sugar)
        {
            this.mapper = mapper;
            this.sugar = sugar;
        }
        /// <summary>
        /// 获取决策层级
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<ManagementOverviewDto>> Handle(ManagementOverviewCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<ManagementOverviewDto>result=new ApiPaging<ManagementOverviewDto>();
            var list = sugar.db.Queryable<NCDSign, ResidentFiles>((a, b) => new object[]
            {
                JoinType.Left,a.Patient_Id==b.ResidentFiles_Id
            }).Select<ManagementOverviewDto>((a, b) => new ManagementOverviewDto
            {
                Patient_Id = a.Patient_Id,
                ResidentFiles_Id = b.ResidentFiles_Id,
                Sign_StartTime = a.Sign_StartTime,
                Sex = b.Sex,
                Age = b.Age,
                Hypertension = b.Hypertension,
                Diabetes = b.Diabetes,
                BMI = b.BMI

            }).ToList();    

            result.TotalCount = list.Count();
            result.TotalPage = (int)Math.Ceiling(list.Count() * 1.0 / request.PageSize);
            list = list.OrderByDescending(x=>x.Patient_Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.list = list.ToList();
            return await Task.FromResult(result);
        }
    }
}
